package com.tcs.email.message;

import javax.mail.MessagingException;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.listener.AcknowledgingMessageListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tcs.email.config.SimpleMailSender;
import com.tcs.model.email.MailSenderInfo;
import com.tcs.util.constant.SystemConstants;

/**
 * 此邮件模块在0.2版本使用此接口. 0.1版本可以调用,但无其他模块在使用.不在废弃范围之内.
 * @serial 0.1 版本的接口使用的是下方的类路径
 * @see com.tsc.email.service.impl.IEmailServiceImpl
* @Title: MessageLogService.java
* @Package com.tsc.email.message
* @author 神经刀
* @date 2018年10月15日
* @version V0.2
 */
@Component(value="kafkaConsumerService")
public class MessageLogService implements AcknowledgingMessageListener<String,String> {
	
	private final Logger logger = LoggerFactory.getLogger(MessageLogService.class);
	
	private SimpleMailSender sms = null;
	
	private MailSenderInfo mailInfo;
	
	ObjectMapper mapper = new ObjectMapper();
	
	public MessageLogService() {
		logger.info("start AcknowledgingMessageListener....");
	}

	@Override
	public void onMessage(ConsumerRecord<String, String> data, Acknowledgment acknowledgment) {
		try {
			mailInfo = mapper.readValue(data.value() , MailSenderInfo.class);
			logger.info(" partition : {} , offset : {} , key : {} , value : {} , xuValue : {} " , data.partition() , data.offset() , data.key() , data.value() , mailInfo);
		} catch (Exception e) {
			logger.error("异常,请在kafka.index寻找此分区以和索引  partition : " + data.partition() +  "offset : " + data.offset() , e);
		}
		try {
			setMailSenderInfoParams();			// 初始化参数
			// 这个类主要来发送邮件
			sms = new SimpleMailSender();
			if (mailInfo.getSendFlag() == 1) {
				sms.sendTextMail(mailInfo); // 发送文体格式
			} else if (mailInfo.getSendFlag() == 2) {
				sms.sendHtmlMail(mailInfo); // 发送HTML格式
			}
		} catch (MessagingException e) {
			logger.error("" , e);
		} finally {
			acknowledgment.acknowledge();
		}
	}
	
	/**
	 * 初始化
	 */
	private void setMailSenderInfoParams() {
		mailInfo.setMailServerHost("smtp.163.com");
		mailInfo.setMailServerPort("25");
		mailInfo.setValidate(true);
		mailInfo.setUserName("wswangbo007@163.com"); // 实际发送者
		mailInfo.setPassword("wswangbo007");// 您的邮箱密码
		mailInfo.setFromAddress("wswangbo007@163.com"); // 设置发送人邮箱地址
		mailInfo.setToAddress("wswangbo007@qq.com"); // 设置接受者邮箱地址
		if (null == mailInfo.getCcs()) {
			mailInfo.setCcs(SystemConstants.EmailConstants.ccs);
		}
		mailInfo.setContent(mailInfo.getContent());
	}

}
